<template>
  <div>
    <div style="width: 150px; height: 150px; overflow: hidden">
      <el-upload v-model:file-list="file"
                 ref="uploadImage"
                 style="height: 30px"
                 list-type="picture-card"
                 :auto-upload="true"
                 :limit="1"
                 :http-request="uploadImageHandler"
      >
        <el-icon><Plus /></el-icon>

        <template #file="{ file }">
          <div>
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
            <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
          </div>
        </template>
      </el-upload>
    </div>

    <el-dialog v-model="dialogVisible">
      <el-image w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script>
import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { uploadFileImage } from '@/api/image'
export default {
  name: 'upload-image',
  components: { Delete, Plus, ZoomIn },
  props: ['modelValue'],
  computed: {
    value: {
      get () {
        console.log(this.modelValue)
        return this.modelValue
      },
      set (value) {
        console.log('setValue', value)
        this.$emit('update:modelValue', value)
      }
    }
  },
  setup () {
    return {
      dialogVisible: ref(false),
      dialogImageUrl: ref(''),
      disabled: ref(false),
      file: ref([])
    }
  },
  methods: {
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove () {
      this.file = []
    },
    uploadImageHandler (request) {
      uploadFileImage(request.file).then(val => {
        this.dialogImageUrl = val.data
        this.value = val.data
      })
    }
  },
  mounted () {
    if (this.file.length === 0 && this.value) {
      this.file.push(
        {
          name: '图片',
          url: this.value
        }
      )
    }
  },
  watch: {
    modelValue: function () {
      this.value = this.modelValue
      if(this.file && this.file[0]){
        this.file[0].url = this.modelValue
      }
    }
  }
}
</script>

<style scoped>

</style>
